package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.feign.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.ThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;

    @Override
    public Long createOrder(OrderDto orderDto) {
        //通过线程工具类获取userId
        String userId = ThreadLocalUtils.getUserId();
        //通过itemId获取item信息
        Long itemId = orderDto.getItemId();
        Item item = itemClient.getItemById(itemId.toString());
        //=========保存订单【OrderMapper】============
        Order order = new Order();
        //设置下单用户
        order.setUserId(Long.valueOf(userId));
        //设置订单状态为未支付
        order.setStatus(1);
        //设置商品金额
        order.setTotalFee(item.getPrice() * orderDto.getNum());
        //设置支付金额
        order.setPaymentType(orderDto.getPaymentType());
        //保存订单
        orderMapper.insert(order);

        //========保存订单明细【OrderDetail】============
        OrderDetail orderDetail = new OrderDetail();
        //订单id
        orderDetail.setOrderId(order.getId());
        //商品规模
        orderDetail.setSpec(item.getSpec());
        //商品数量
        orderDetail.setNum(orderDto.getNum());
        //商品图片
        orderDetail.setImage(item.getImage());
        //商品标题
        orderDetail.setName(item.getName());
        //保存订单明细
        orderDetailMapper.insert(orderDetail);

        //============保存物流信息【OrderLogistics】============
        OrderLogistics orderLogistics = new OrderLogistics();
        //获取收货地址
        Address address= userClient.findAddressById(orderDto.getAddressId());
        //将地址信息-->订单物流信息
        BeanUtils.copyProperties(address,orderLogistics);
        //设置订单id
        orderLogistics.setOrderId(order.getId());
        //保存物流信息-->数据库
        orderLogisticsMapper.insert(orderLogistics);

        //============扣减库存【ItemClient】==============
        itemClient.updateStock(itemId,orderDto.getNum());
        return order.getId();
    }
}
